package com.sabm.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sabm.model.Account;
import com.sabm.model.Contact;
import com.sabm.model.Phone;
import com.sabm.model.Role;

@Repository
public class UserDAOImpl implements UserDAO {

	@Autowired
    private SessionFactory sessionFactory;
	@Autowired
	private RoleDAOImpl roleDAO;
	
	public void save(Account account){
		sessionFactory.getCurrentSession().save(account);
	}
	//
	public void delete(Account account){
		sessionFactory.getCurrentSession().delete(account);
	}
	//
	public void update(Account account){
		sessionFactory.getCurrentSession().update(account);
	}
	//
	public void saveOrUpdateRole(Role role){
		roleDAO.saveOrUpdate(role);
	}
	//
	public Account get(int id){
		Account account = (Account)sessionFactory.getCurrentSession().get(Account.class, id);
		return account;
	}
	// get account by username
	public Account get(String username){
		Query query = sessionFactory.getCurrentSession().createQuery("from Account where username = :username ");
		query.setParameter("username", username);
		List list = query.list();
		if(list.size()>0){
			return (Account)list.get(0);
		}else{
			return null;
		}
	}
	// get list accounts
	public List<Account> getListAccount(){
		Query query = sessionFactory.getCurrentSession().createQuery("from Account ");
		List<Account> list = query.list();
		return list;
	}
	//
	public boolean checkUsername(String username){
		Query query = sessionFactory.getCurrentSession().createQuery("from Account where username = :username ");
		query.setParameter("username", username);
		List list = query.list();
		if(list.size()>0){
			return true;
		}else{
			return false;
		}
	}

}
